<template>
  <div>
    <RePage>
      <MyFormCreate :clear-event="getTableList" v-model="searchForm" :rule="searchFormRules" :key="key">
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <div>
        <el-button v-auth="'system.factory.create'" type="primary" :icon="Plus" @click="add">添加</el-button>
        <el-button type="primary" plain :disabled="selectionData.length == 0" @click="exportsfile(1)">批量导出</el-button>
        <el-button type="primary" plain @click="exportsfile(2)">导入</el-button>
      </div>
      <pure-table class="mt-5" :data="tableData.data" @selection-change="selectionChange"
        :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border :isShowPag="false">
        <template #productName="{ row }">
          <el-tag class="mr-[10px]" v-for="(item, index) in row.productName" :key="index">
            {{ isNullOrEmpty(item) }}
          </el-tag>
          {{ isNullOrEmpty(row?.productName) }}
        </template>
        <template #action="{ row }">
          <el-space>
            <sj-link custom-type="sblue" :underline="false" @click="goProduct(row)" v-auth="'system.product.select'">产品</sj-link>
            <sj-link custom-type="sblue" :underline="false" @click="info(row)">查看</sj-link>
            <sj-link custom-type="sblue" :underline="false" @click="edit(row)"
              v-auth="'system.factory.update'">编辑</sj-link>
            <sj-link custom-type="sred" :underline="false" @click="deletes(row)"
              v-auth="'system.factory.remove'">删除</sj-link>
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import ReTable from "@/components/ReTable/index.vue";
import importManufacturer from './import-manufacturer.vue'
import editForm from "./form.vue";
import infos from "./info.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, getInfo, addInfo, editInfo, deleteInfo, factoryexport, factoryimportall } from '@/api/manage/product-management/manufacturer-management/index';
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { addDialog } from "@/components/ReDialog";
import { cloneDeep, isAllEmpty, deviceDetection, debounce } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
const selectionData = ref([])
const searchForm = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const router = useRouter()
const tableData = reactive({
  data: [],
  total: 0,
});
const selectionChange = data => {
  selectionData.value = data;
};
const searchFormRules = [
  // {
  //   type: 'input', field: 'id', title: titles.id, value: null, props: {
  //     placeholder: prompt.id, clearable: true
  //   }
  // },
  {
    type: 'input', field: 'factoryName', title: titles.factoryName, value: null, props: {
      placeholder: prompt.factoryName, clearable: true
    }
  },
  // {
  //   type: 'input', field: 'productName', title: titles.productName, value: null, props: {
  //     placeholder: prompt.productName, clearable: true
  //   }
  // },
  // {
  //   type: 'input', field: 'contactName', title: titles.contactName, value: null, props: {
  //     placeholder: prompt.contactName, clearable: true
  //   }
  // },
  // {
  //   type: 'input', field: 'contactPhone', title: titles.contactPhone, value: null, props: {
  //     placeholder: prompt.contactPhone, clearable: true
  //   }
  // },
  // {
  //   type: 'input', field: 'remark', title: titles.remark, value: null, props: {
  //     placeholder: prompt.remark, clearable: true
  //   }
  // },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];

const roleTableConfig = [
  { type: "selection", align: "left", fixed: 'left' },
  { prop: 'id', width: 100, label: titles.id, fixed: 'left' },
  { prop: 'factoryName', label: titles.factoryName, minWidth: 150 },
  { prop: 'contactName', label: titles.contactName, minWidth: 100 },
  { prop: 'contactPhone', label: titles.contactPhone, minWidth: 120 },
  // { slot: 'productName', label: titles.productName, minWidth: 120 },
  { prop: 'remark', label: titles.remark, minWidth: 150 },
  { slot: 'action', label: titles.action, width: 180, fixed: 'right' },
];
onMounted(() => {
  getTableList()
});
const goProduct=(item)=>{
  router.push(`/product-management/product-type?factoryName=${item.factoryName}`)
}
// 获取列表数据
const getTableList = () => {
  getList(searchForm.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchForm.value, defaultSearchForm())
  key.value++
  getTableList()
}
// 详情
const info = (row) => {
  addDialog({
    title: `厂家详情`,
    hideFooter: true,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoForm()
      }
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          showInfo.value = res.result
          options.props.formInline = res.result
        }
      }).finally(() => {
        options.props.isLoading = false
      })
    },
  });
}
// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog('添加厂家')
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑厂家", row)
}
// 删除
const deletes = (row) => {
  ElMessageBox.confirm(
    '确认删除这条数据?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: [row.id] }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "添加厂家", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm()
        }
        getInfo({ id: row.id }).then(res => {
          if (res.code == 200) {
            showInfo.value = res.result
            options.props.formInline = res.result
          }
        }).finally(() => {
          options.props.isLoading = false
        })
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm()
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加厂家") {
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
function exportsfile(type) {
  if (type == 1) {
    factoryexport({ factoryIds: selectionData.value.map(item => item.id) }).then(res => {
      let data = res.result
      // 创建a标签
      var a = document.createElement('a');
      // 设置导出文件名称
      a.download = "data.json";
      a.style.display = "none";
      // 转成字符串形式
      var dat = JSON.stringify(data, null, 4);
      // 转成blob流
      var blob = new Blob([dat], {
        type: "application/json"
      });
      // 将blob流转成url
      a.href = URL.createObjectURL(blob);
      document.body.appendChild(a);
      // 触发a标签 进行下载
      a.click();
      // 移出标签
      document.body.removeChild(a);
    })
  } else {
    addDialog({
      title: `文件导入`,
      width: "800px",
      draggable: true,
      props: {
        importForm: {
          file: null
        }
      },
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(importManufacturer, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        function chores() {
          message(`操作成功`, {
            type: "success"
          });
          done(); // 关闭弹框
          getTableList(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid && !options.props?.isLoading) {
            // console.log("formData", formData);
            // 表单规则校验通过
            options.props.isLoading = true;
            let formData = new FormData();
            for (let key in options.props.importForm) {
              formData.append(key, options.props.importForm[key]);
            }
            factoryimportall(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        })
      }
    });
  }
}
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped></style>
